package com.zhiyume.api.controller;

import com.zhiyume.controller.BaseController;
import com.zhiyume.dao.entity.TUser;
import com.zhiyume.dto.*;
import com.zhiyume.service.RegisterService;
import com.zhiyume.service.UserService;
import com.zhiyume.service.common.ConstantEnum;
import com.zhiyume.service.util.StringUtil;
import com.zhiyume.util.RedisClient;
import com.zhiyume.util.TypeConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wang on 17/11/1.
 */
@RestController
@Api(tags = "登录注册")
public class LoginAction extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(LoginAction.class);
    private static final String MODULE = LoginAction.class.getName();
    @Autowired
    private UserService userService;

    @Autowired
    private RegisterService registerService;

    @Autowired
    private RedisClient redisClient;

    @RequestMapping(value = "/api/login", method = RequestMethod.POST)
    @ApiOperation(value = "登录接口")
    public void login(LoginReqDTO reqDTO, HttpServletResponse response){
        BaseResponse res = new BaseResponse();
        if(StringUtil.isBlank(reqDTO.getUserName())) {
            res.setErrType(ConstantEnum.CONSTANT_MISS_USERANME.getErrType());
            res.setErrMsg(ConstantEnum.CONSTANT_MISS_USERANME.getErrMsg());
            this.responseJsonStr(response,res);
            return;
        }
        if(StringUtil.isBlank(reqDTO.getPassword())) {
            res.setErrType(ConstantEnum.CONSTANT_MISS_PASSWORD.getErrType());
            res.setErrMsg(ConstantEnum.CONSTANT_MISS_PASSWORD.getErrMsg());
            this.responseJsonStr(response,res);
            return;
        }
        LoginResDTO dto = userService.Login(reqDTO.getUserName(),reqDTO.getPassword());
        if(dto.getuId()<0){
            res.setErrType(ConstantEnum.CONSTANT_ERROR_PASSWORD.getErrType());
            res.setErrMsg(ConstantEnum.CONSTANT_ERROR_PASSWORD.getErrMsg());
            this.responseJsonStr(response,res);
            return;
        }
        //JSONObject jsonObject = JSONObject.parseObject(returnStr);
        Map<String,Object> cookies = new HashMap<>();
        //if(jsonObject.getString("errType").equals(ConstantEnum.CONSTANT_SUCCESS.getErrType())){
        if(res.getErrType().equals(ConstantEnum.CONSTANT_SUCCESS.getErrType())){
            cookies.put("token",dto.getToken());
            cookies.put("uid",dto.getuId());
            addCookies(response,cookies,null);
        }
        List<LoginResDTO> data = new ArrayList<>();
        data.add(dto);
        res.setData(data);
        this.responseJsonStr(response,res);
        return ;
    }


    @RequestMapping(value = "/api/register", method = RequestMethod.POST)
    @ApiOperation(value = "注册接口")
    public void register(RegisterReqDTO reqDTO, HttpServletResponse response){
        BaseResponse res = new BaseResponse();
        if(StringUtil.isBlank(reqDTO.getUserName())) {
            res.setErrType(ConstantEnum.CONSTANT_MISS_USERANME.getErrType());
            res.setErrMsg(ConstantEnum.CONSTANT_MISS_USERANME.getErrMsg());
            this.responseJsonStr(response,res);
            return;
        }
        if(StringUtil.isBlank(reqDTO.getPassword())) {
            res.setErrType(ConstantEnum.CONSTANT_MISS_PASSWORD.getErrType());
            res.setErrMsg(ConstantEnum.CONSTANT_MISS_PASSWORD.getErrMsg());
            this.responseJsonStr(response,res);
            return;
        }

        RegisterResDTO registerResDTO = registerService.register(reqDTO);
        if (registerResDTO.getuId()==-1L){
            res.setErrType(ConstantEnum.CONSTANT_USER_EXISTS.getErrType());
            res.setErrMsg(ConstantEnum.CONSTANT_USER_EXISTS.getErrMsg());
            this.responseJsonStr(response,res);
        }
        //JSONObject jsonObject = JSONObject.parseObject(returnStr);
        Map<String,Object> cookies = new HashMap<>();
        //if(jsonObject.getString("errType").equals(ConstantEnum.CONSTANT_SUCCESS.getErrType())){
        if(res.getErrType().equals(ConstantEnum.CONSTANT_SUCCESS.getErrType())){
            cookies.put("token",registerResDTO.getToken());
            cookies.put("uid",registerResDTO.getuId());
            addCookies(response,cookies,null);
        }
        List<RegisterResDTO> data = new ArrayList<>();
        data.add(registerResDTO);
        res.setData(data);
        this.responseJsonStr(response,res);
        return ;
    }

    @RequestMapping(value = "/api/logout", method = RequestMethod.POST)
    @ApiOperation(value = "注销接口")
    public BaseResponse logout(LoginReqDTO reqDTO, @RequestHeader(value=TypeConstants.TOKEN_API_KEY,defaultValue = "")String token){
        BaseResponse res = new BaseResponse();
        if(StringUtil.isBlank(reqDTO.getUserName())) {
            res.setErrType(ConstantEnum.CONSTANT_MISS_USERANME.getErrType());
            res.setErrMsg(ConstantEnum.CONSTANT_MISS_USERANME.getErrMsg());
            return res;
        }
        if(StringUtil.isBlank(reqDTO.getPassword())) {
            res.setErrType(ConstantEnum.CONSTANT_MISS_PASSWORD.getErrType());
            res.setErrMsg(ConstantEnum.CONSTANT_MISS_PASSWORD.getErrMsg());
            return res;
        }
        Long uid= -1L;
        LoginResDTO dto = new LoginResDTO();
        dto.setuId(-1l);
        try{
            logger.info(ConstantEnum.CONSTANT_TOKEN_PRE.getErrType() + token);
            String o = redisClient.get(ConstantEnum.CONSTANT_TOKEN_PRE.getErrType() + token);
            if(StringUtil.isNotBlank(o)) {
                uid = Long.valueOf(o);
            }else{
                res.setErrType(ConstantEnum.CONSTANT_USER_INFO_TIMEOUT.getErrType());
                res.setErrMsg(ConstantEnum.CONSTANT_USER_INFO_TIMEOUT.getErrMsg());
                return res;
            }
        }catch (Exception e){
            res.setErrType(ConstantEnum.CONSTANT_SYS_ERROR.getErrType());
            res.setErrMsg(ConstantEnum.CONSTANT_SYS_ERROR.getErrMsg());
            logger.error(e.getMessage());
        }

        dto = userService.Login(reqDTO.getUserName(),reqDTO.getPassword());
        if(Long.valueOf(dto.getuId())<0) {
            res.setErrType(ConstantEnum.CONSTANT_LOGINOUT_ERROR.getErrType());
            res.setErrMsg(ConstantEnum.CONSTANT_LOGINOUT_ERROR.getErrMsg());
            return res;
        }

        LoginResDTO loginResDTO = userService.Logout(uid,token);
        res.setData(loginResDTO);

        return res;
    }


    @RequestMapping(value = "/api/userInfo", method = {RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value = "获取用户信息")
    @ResponseBody
    public BaseResponse userInfo(@RequestHeader(value=TypeConstants.TOKEN_API_KEY,defaultValue = "")String token){
        BaseResponse res = new BaseResponse();
        Long uid= -1L;
        try{
            logger.info(ConstantEnum.CONSTANT_TOKEN_PRE.getErrType() + token);
            String o = redisClient.get(ConstantEnum.CONSTANT_TOKEN_PRE.getErrType() + token);
            if(StringUtil.isNotBlank(o)) {
                uid = Long.valueOf(o);
            }else{
                res.setErrType(ConstantEnum.CONSTANT_USER_INFO_TIMEOUT.getErrType());
                res.setErrMsg(ConstantEnum.CONSTANT_USER_INFO_TIMEOUT.getErrMsg());
                return res;
            }
        }catch (Exception e){
            res.setErrType(ConstantEnum.CONSTANT_SYS_ERROR.getErrType());
            res.setErrMsg(ConstantEnum.CONSTANT_SYS_ERROR.getErrMsg());
            logger.error(e.getMessage());
        }

        TUser tUser = userService.selectUserById(uid);
        res.setData(tUser);

        return res;
    }
}

